package servlet;

import dao.PostDao;
import dao.PostDaoImpl;
import io.jsonwebtoken.Claims;
import org.json.JSONObject;
import redis.RedisDao;
import redis.RedisDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static util.JwtUtil.parseJWT;
import static util.JwtUtil.validateJWT;

/**
 * @author moyv
 */
public class DeltePostServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("删除帖子数据中");
        req.setCharacterEncoding("UTF-8");
        String token = req.getParameter("token");
        int result = 0;
        if (validateJWT(token)) {
            String postId = String.valueOf(req.getParameter("postId"));
            if (postId != null) {
                int id=Integer.parseInt(postId);
                Claims claims=parseJWT(token);
                int account=Integer.parseInt(claims.getId());
                PostDao dao = new PostDaoImpl();
                RedisDao dao1 = new RedisDaoImpl();
                if (dao.delPost(id) && dao1.delPost(id,account)) {
                    result = 1;
                } else {
                    result = 2;
                }
            }
        } else {
            System.out.println(getClass().getName() + ": 非法token信息");
        }
        JSONObject obj = new JSONObject();
        System.out.println("result="+result);
        obj.put("result", result);

        // 设置响应内容类型
        resp.setContentType("text/json; charset=utf-8");
//        输出数据
        PrintWriter out = resp.getWriter();
        out.print(obj);
        System.out.println(obj);
    }
}
